<?php

require '../inc/init.php';

$act = isset($_GET['action']) ? $_GET['action'] : 'type';

//生成礼包卡号
if($act == 'make')			
{
	$op = isset($_GET['op']) ? $_GET['op'] : null;
	if($op == 'generate')			//生成礼品卡号
	{
		$num = isset($_POST['num']) ? intval($_POST['num']) : 500;
		$length = isset($_POST['length']) ? $_POST['length'] : 8;
		$code_types = isset($_POST['code_types']) ? $_POST['code_types'] : 0;
		while($num)
		{
			$actCode = generatePassword($length);
			$sql = "insert into tb_ad_activity_code (code,code_type,status,created_date,last_modified_date) values ('$actCode',$code_types,1,NOW(),NOW())";
			$flag = $db->query($sql);
			if(!$flag)
			{
				exit('0');
			}
			$num--;
		}
		gourl('generate success!', 'active_code.php?action=make');
	}
	
	$sql = "SELECT id,act_type FROM tb_actcode_type";
	$code_types = $db->getAll($sql);

	$code_type = isset($_GET['code_type']) ? $_GET['code_type'] : NULL;
	$T->assign('act',$act);
	$T->assign('code_type',$code_type);
	$T->assign('code_types',$code_types);
	$T->display('active_code.html');
	exit;
}
elseif($act == 'type') 			//礼包卡类型
{
	$op = isset($_GET['op']) ? $_GET['op'] : null;
	if($op == 'add')					//添加新的礼品卡类型
	{
		$code_type_name = isset($_POST['code_type_name']) ? trim(strip_tags($_POST['code_type_name']) ): NULL;

		if(empty($code_type_name))
		{
			gourl('field_empty', 'active_code.php');
		}
		
		if(strlen($code_type_name)>30)
		{
			gourl('font_toomany', 'active_code.php');
		}
		
		$sql = "INSERT INTO tb_actcode_type SET act_type = '$code_type_name'";
		$isAdded = $db->query($sql);
	}
	elseif($op== 'delete')				//删除礼品卡类型
	{
		$type_id = isset($_GET['typeId']) ?$_GET['typeId'] : null;
		
		$sql = "SELECT * FROM tb_ad_activity_code WHERE code_type = $type_id";
		$flag = $db->getOne($sql);
		if($flag)
		{
			gourl('Please delete codes of selected code_type first!', 'active_code.php');
		}
		
		$sql = "DELETE FROM tb_actcode_type WHERE id = $type_id";
		$isDeleted = $db->query($sql);
	}
	
	$sql = "SELECT id,act_type FROM tb_actcode_type WHERE id>1000";			//普通礼品卡号大于1000，防止和三种已有类型混淆
	$actTypes = $db->getAll($sql);
	
	$T->assign('act',$act);
	$T->assign('actTypes',$actTypes);
	$T->display('active_code.html');
	exit;
}
elseif($act == 'list')				//激活码列表
{
	$op = isset($_GET['op']) ? $_GET['op'] : null;
	$where = '';
	
	if($op == 'filter' )			//过滤
	{
		//礼包卡号过滤
		$act_code = isset($_REQUEST['act_code']) ? $_REQUEST['act_code'] : NULL;
		if(!empty($act_code))
		{
			$where .= " and c.code = '$act_code'";
		}
		$T->assign('act_code',$act_code);
		
		//生成时间过滤
		$generate_time = isset($_REQUEST['generate_time']) ? $_REQUEST['generate_time'] : NULL;
		if(!empty($generate_time))
		{
			$where .= " and c.created_date = '$generate_time'";
		}
		$T->assign('generate_time',$generate_time);
		
		//发送时间过滤
		$send_time = isset($_REQUEST['send_time']) ? $_REQUEST['send_time'] : NULL;
		if(!empty($generate_time))
		{
			$where .= " and c.last_modified_date = '$send_time'";
		}
		$T->assign('send_time',$send_time);
		
		//礼包卡类型过滤
		$codeType = isset($_REQUEST['codeTypes']) ? $_REQUEST['codeTypes'] : 0;
		if(!empty($codeType))
		{
			$where .= " and c.code_type = $codeType";
		}
		$T->assign('codeType',$codeType);
		
		//是否使用过滤
		$is_used = isset($_POST['is_used']) ? $_POST['is_used'] : 0;
		if(!empty($is_used))
		{
			$where .= " and c.status = $is_used"; 
		}
		$T->assign('is_used',$is_used);

		//目标服务器过滤
		$server = isset($_REQUEST['server']) && !empty($_REQUEST['server']) ? $_REQUEST['server'] : 0;			//0:全部；1:未使用；2：已使用
		if(!empty($server))
		{
			$where .= " and c.server_id  REGEXP $server";
		}
		$T->assign('server',$server);
		
		//一次显示礼包卡数量
		$codeNum = isset($_POST['codeNum']) && !empty($_POST['codeNum']) ? $_POST['codeNum'] : 0;
		if(!empty($codeNum))
		{
			$where .= " limit $codeNum";
		}
	}
	
	$sql = "SELECT c.id,t.act_type,`code` ,server_id,c.created_date,c.last_modified_date,c.status
				FROM tb_ad_activity_code AS c
				LEFT JOIN tb_actcode_type as t ON t.id = c.code_type
				WHERE 1 ".$where;
	$codes = array();
	$i = 0;
	$rs = $db->query($sql);
	while($row = $db->fetchRow($rs))
	{
		$codes[$i] = $row;
		$codes[$i]['server_id'] = explainServerName($row['server_id']); 
		$codeArray[] = $row['code'];
		$i++;
	}
	
	//将过滤后的卡号发送至指定单服	
	if(($op == 'filter' && isset($_POST['send'])) || ($op == 'filter' && isset($_POST['remote_delete'])))
	{
		$platforms = isset($_POST['platform_id']) ?$_POST['platform_id']:0;
		$servers = isset($_POST['server_id'])? $_POST['server_id']:0;
		
		//没有指定目标服务器
		if(empty($servers))
		{
			gourl('please input servers!', 'active_code.php?action=list');
		}
		
		//没有指定礼品卡类型
		if(empty($codeType))
		{
			gourl('please input codetype!', 'active_code.php?action=list');
		}
		
		//检测选定的礼品卡是否都已经发送
		if(isset($_POST['remote_delete']))
		{
			$codes = check_is_send($codes,0);		//都已发送的才删除
		}
		else 
		{
			$codes = check_is_send($codes,1);		//都未发送的才发送
		}
		
		//礼品卡号都已使用，已发送
		if(empty($codes))
		{
			gourl('The codes have been send!', 'active_code.php?action=list');
		}
		
		$action = isset($_POST['remote_delete']) ? 2 : 1;		//1:默认add  2:删除
		
		require_once  '../inc/server_config.php';
		require_once '../inc/socket.class.php';
		
		//循环发送
		foreach($servers as $k=>$v)
		{
			$socket_gateway['address'] 	= $socketList[$v]['address'];
			$socket_gateway['port'] 		= $socketList[$v]['port'];
			
			//与服务端通信
			$sendData = array(
											array('type'=>1,'data'=>$action),					//是否删除
											array('type'=>7,'data'=>$codeType),				//礼包卡类型
											array('type'=>6,'data'=>$codeArray),				//卡号
									);
							
			$protocol = 'activityPackageOpt';
			
			$gamesocket = new gamesocket();
			$receive = $gamesocket->send($sendData, $protocol);
			if($receive['retcode'] == '00000000')
			{
				continue;
			}
			else 
			{
				gourl('operate_fail', 'active_code.php?action=list');
			}
		}
		
		//全部发送成功后，重置数据库改激活码的状态，以及发送到的目标服务器
		if($action == 1)
		{
			code_send_status('add',$codes,$servers);
		}
		else 
		{
			code_send_status('del',$codes,$servers);
		}
		
		//全部发送成功
		gourl('operate_success', 'active_code.php?action=list');
		
	}
	else 	if($op == 'filter' && isset($_POST['local_delete']))
	{
		if(empty($codes))
		{
			gourl('please input codes!', 'active_code.php?action=list');
		}
		
		$codes = check_is_send($codes, 1);
		if(empty($codes))
		{
			gourl('The selected codes are sended,So not allowed deleted in localServer!', 'active_code.php?action=list');
		}
		
		code_send_status('delete', $codes, $server);
		
		gourl('The selected codes are  deleted in localServer!', 'active_code.php?action=list');
		
	}
	
	$sql = "SELECT id,act_type FROM tb_actcode_type";
	$actTypes = $db->getAll($sql);
	
	//平台列表
	$platforms = getPlatforms();
	
	//服务器列表
	$server_list = getServerInfo();
	
	$T->assign('platforms',$platforms);
	$T->assign('server_list',$server_list);
	
	$T->assign('codeNum',$codeNum);
	$T->assign('act',$act);
	$T->assign('actTypes',$actTypes);
	$T->assign('codes',$codes);
	$T->display('active_code.html');
	exit;
}


/**
 * 生成随机码
 * @param int $length
 * @return array 随机码数组
 */
function generatePassword($length=8)
{
    $chars = array_merge(
    				 	range(0,9),
                     	range('a','z'),
                    	range('A','Z'),
                     	array('!','@','$','%','^','&','*'));
    shuffle($chars);
    $password = '';
    for($i=0; $i<$length; $i++) {
        $password .= $chars[$i];
    }
    return $password;
}

/**
 * 央服卡号发送至单服后，更新状态
 * @param unknown_type $operate
 * @param unknown_type $codes
 * @return 1 更新成功;0 更新失败
 */
function code_send_status($operate,$codes,$server)
{
	global $db;
	$server = implode('|', $server);
	foreach($codes  as $k=>$v)
	{
		if($operate == 'add')
		{
			$id = $v['id'];
			$sql = "UPDATE tb_ad_activity_code SET `status` = 2, server_id =' $server',last_modified_date = NOW()  WHERE id = $id";		//status=2已使用，发送至单服
		}
		else 
		{
			$id = $v['id'];
			$sql = "DELETE FROM tb_ad_activity_code  WHERE id = $id";			//单服已经删除,本地也一起删除
		}
		$flag = $db->query($sql);
		
		if($flag)
		{
			continue;
		}
		else 
		{
			return $id;
		}
	}
	return true;
}

/**
 * 返回尚未使用的礼品卡号
 * @param unknown_type $codes
 */
function check_is_send($codes,$isdelete)
{
	global $db;
	$temp = array();
	foreach($codes as $k=>$v)
	{
		if($v['status'] == 2)		//已发送
		{
			if($isdelete == 1)	//发送
			{
				continue;
			}
			else 
			{
				$temp[] = $v;
			}
		}
		else if($v['status'] == 1)		//未发送
		{
			if($isdelete == 1)
			{
				$temp[] = $v;
			}
			else 
			{
				continue;
			}
		}
	}
	return $temp;
}





